package cn.iocoder.ny.module.mall.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 阿里短信云工具类
 */
@Component
public class AliSmsUtils {
    /**
     * 发送短信验证码
     * @param phone
     * @param codeNum 验证码位数
     * @param signName 短信签名
     * @param templateCode 模版CODE
     * @param accessKeyId 阿里云的 Access Key ID
     * @param accessKeySecret Access Key Secret
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static String sendSms(String phone,int codeNum,String signName,String templateCode,String accessKeyId,String accessKeySecret) throws ExecutionException, InterruptedException {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
        .build());
        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
        //生成随机验证码,前后不能带数字0
        String numbers = randomNumbers(codeNum);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam("{code:"+numbers+"}")
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        String code = resp.getBody().getCode();
        client.close();
        if ("OK".equals(code)){
            return numbers;
        }else {
            return code;
        }

    }


    private static final Random RANDOM = new Random();
    private static final int[] NON_ZERO_DIGITS = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    /**
     * 生成指定长度的数字验证码，首尾不含0
     *
     * @param codeNum 验证码长度
     * @return 生成的验证码
     */
    public static String randomNumbers(int codeNum) {
        if (codeNum < 2) {
            throw new IllegalArgumentException("验证码长度必须大于等于2");
        }

        StringBuilder sb = new StringBuilder(codeNum);

        // 首位数字
        sb.append(NON_ZERO_DIGITS[RANDOM.nextInt(NON_ZERO_DIGITS.length)]);

        // 中间数字
        for (int i = 1; i < codeNum - 1; i++) {
            sb.append(RANDOM.nextInt(10));
        }

        // 尾部数字
        sb.append(NON_ZERO_DIGITS[RANDOM.nextInt(NON_ZERO_DIGITS.length)]);

        return sb.toString();
    }



}
